<?php

namespace App\Services\Core\Store\Kaisen;

use App\Services\Core\Store\Pingan\PinganConfig;

/**
*
* AES加密和解密
*
*/
class AESUtils
{


    public static function Encrypt($data,$key,$iv)
    {
        $ciphertext = openssl_encrypt($data,"AES-128-CBC", $key, OPENSSL_RAW_DATA, $iv);
        return strtolower(self::parseByte2HexStr($ciphertext));
    }




    public static function Decrypt($data,$key,$iv)
    {
        $data = self::parseHexStr2Byte($data);
        $decryptedData = openssl_decrypt($data,"AES-128-CBC",$key,OPENSSL_RAW_DATA, $iv);
        return $decryptedData;

    }



    public static function parseByte2HexStr($str)
    {
        $en = '';
        for ($i = 0; $i < strlen($str); $i++) {
            $hex = bin2hex($str[$i]);
            if (strlen($hex) == 1) {
                $hex = '0' + $hex;
            }
            $en .= strtoupper($hex);
        }
        return $en;

    }


    // 将十六进制字符串转换成字符子节
    public static function parseHexStr2Byte($str)
    {
        $len = strlen($str);
        $en = '';
        for($i=0;$i<$len/2;$i++){
            $high = intval($str[$i*2],16);
            $low  = intval($str[$i*2+1],16);
            $en  .= chr($high*16+$low);
        }
        return $en;
    }

}
